// 仪表板JavaScript功能

// 切换标签页
function showTab(tabName) {
    // 隐藏所有标签内容
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // 移除所有按钮的active类
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 显示选中的标签内容
    document.getElementById(tabName + '-tab').classList.add('active');
    
    // 激活对应的按钮
    event.target.classList.add('active');
    
    // 加载对应的数据
    if (tabName === 'member-worktime') {
        loadMemberWorktimeData();
    } else if (tabName === 'worktime') {
        loadWorktimeStats();
    }
}



// 加载成员工时数据
async function loadMemberWorktimeData(filters = {}) {
    try {
        // 构建查询参数
        const params = new URLSearchParams();
        if (filters.period) params.append('period', filters.period);
        if (filters.name) params.append('name', filters.name);
        
        const url = `/api/member-worktime-data${params.toString() ? '?' + params.toString() : ''}`;
        const response = await fetch(url);
        const data = await response.json();
        
        const tbody = document.getElementById('member-worktime-tbody');
        tbody.innerHTML = '';
        
        // 计算统计信息
        let totalUsedWorktime = 0;
        let totalRequirementWorktime = 0;
        let totalTicketWorktime = 0;
        let totalBugWorktime = 0;
        
        data.forEach(member => {
            totalUsedWorktime += member.used_worktime || 0;
            totalRequirementWorktime += member.requirement_worktime || 0;
            totalTicketWorktime += member.ticket_worktime || 0;
            totalBugWorktime += member.bug_worktime || 0;
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${member.name}</td>
                <td>${member.statistics_period}</td>
                <td>${member.role || '-'}</td>
                <td>${member.saturation_rate ? member.saturation_rate.toFixed(1) + '%' : '-'}</td>
                <td>${(member.used_worktime || 0).toFixed(1)}</td>
                <td>${(member.requirement_worktime || 0).toFixed(1)}</td>
                <td>${(member.ticket_worktime || 0).toFixed(1)}</td>
                <td>${(member.bug_worktime || 0).toFixed(1)}</td>
                <td><button class="btn btn-sm" onclick="goToMemberWorktimeDetail('${member.name}', '${member.statistics_period}')">查看详情</button></td>
            `;
            tbody.appendChild(row);
        });
        
        // 更新筛选状态显示
        updateMemberWorktimeFilterStatus(data.length, {
            totalUsedWorktime,
            totalRequirementWorktime,
            totalTicketWorktime,
            totalBugWorktime
        }, filters);
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #6c757d;">暂无数据</td></tr>';
        }
        
        // 隐藏加载状态
        showMemberWorktimeLoadingState(false);
        
    } catch (error) {
        console.error('加载成员工时数据失败:', error);
        showMessage('加载成员工时数据失败', 'error');
        // 隐藏加载状态
        showMemberWorktimeLoadingState(false);
    }
}

// 应用成员工时筛选条件
function applyMemberWorktimeFilters() {
    const filters = {
        period: document.getElementById('member-period-filter').value,
        name: document.getElementById('member-name-filter').value.trim()
    };
    
    // 移除空值
    Object.keys(filters).forEach(key => {
        if (!filters[key]) {
            delete filters[key];
        }
    });
    
    // 显示加载状态
    showMemberWorktimeLoadingState(true);
    
    loadMemberWorktimeData(filters);
}

// 清空成员工时筛选条件
function clearMemberWorktimeFilters() {
    document.getElementById('member-period-filter').value = '';
    document.getElementById('member-name-filter').value = '';
    
    // 重新加载所有数据
    loadMemberWorktimeData();
}

// 显示成员工时加载状态
function showMemberWorktimeLoadingState(isLoading) {
    const tbody = document.getElementById('member-worktime-tbody');
    const filterButtons = document.querySelectorAll('#member-worktime-tab .filter-buttons .btn');
    
    if (isLoading) {
        tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #667eea;"><i>正在加载数据...</i></td></tr>';
        filterButtons.forEach(btn => btn.disabled = true);
    } else {
        filterButtons.forEach(btn => btn.disabled = false);
    }
}

// 更新成员工时筛选状态显示
function updateMemberWorktimeFilterStatus(recordCount, stats, filters) {
    const statusElement = document.getElementById('member-worktime-filter-status');
    const countElement = document.getElementById('member-worktime-filter-count');
    const summaryElement = document.getElementById('member-worktime-filter-summary');
    
    // 更新记录数
    countElement.textContent = recordCount;
    
    // 构建筛选条件摘要
    const filterSummary = [];
    if (filters.period) {
        filterSummary.push(`周期: ${filters.period}`);
    }
    if (filters.name) {
        filterSummary.push(`姓名: ${filters.name}`);
    }
    
    // 添加统计信息
    const statsInfo = [];
    if (stats.totalUsedWorktime > 0) {
        statsInfo.push(`总已用工时: ${stats.totalUsedWorktime.toFixed(1)}人天`);
    }
    if (stats.totalRequirementWorktime > 0) {
        statsInfo.push(`总需求工时: ${stats.totalRequirementWorktime.toFixed(1)}人天`);
    }
    if (stats.totalTicketWorktime > 0) {
        statsInfo.push(`总工单工时: ${stats.totalTicketWorktime.toFixed(1)}人天`);
    }
    if (stats.totalBugWorktime > 0) {
        statsInfo.push(`总Bug工时: ${stats.totalBugWorktime.toFixed(1)}人天`);
    }
    
    // 组合显示信息
    let summaryText = '';
    if (filterSummary.length > 0) {
        summaryText += `筛选条件: ${filterSummary.join(', ')}`;
    }
    if (statsInfo.length > 0) {
        if (summaryText) summaryText += ' | ';
        summaryText += statsInfo.join(', ');
    }
    
    summaryElement.textContent = summaryText;
    
    // 显示或隐藏状态栏
    if (recordCount > 0 || Object.keys(filters).length > 0) {
        statusElement.style.display = 'block';
        statusElement.classList.add('show');
    } else {
        statusElement.style.display = 'none';
        statusElement.classList.remove('show');
    }
}

// 加载成员工时筛选选项数据
async function loadMemberWorktimeFilterOptions() {
    try {
        const response = await fetch('/api/member-worktime-filter-options');
        const data = await response.json();
        
        // 存储到全局变量
        window.memberWorktimeFilterOptions = data;
        
        // 填充成员姓名数据列表
        const nameList = document.getElementById('member-name-list');
        nameList.innerHTML = '';
        data.names.forEach(name => {
            const option = document.createElement('option');
            option.value = name;
            nameList.appendChild(option);
        });
        
        // 设置默认的统计周期为最新的周期
        if (data.periods && data.periods.length > 0) {
            document.getElementById('member-period-filter').value = data.periods[0];
        }
        
    } catch (error) {
        console.error('加载成员工时筛选选项失败:', error);
    }
}





// 加载项目工时统计数据
async function loadWorktimeStats(filters = {}) {
    try {
        // 构建查询参数
        const params = new URLSearchParams();
        if (filters.period) params.append('period', filters.period);
        if (filters.project) params.append('project', filters.project);
        if (filters.system) params.append('system', filters.system);
        
        const url = `/api/project-worktime-stats${params.toString() ? '?' + params.toString() : ''}`;
        const response = await fetch(url);
        const data = await response.json();
        
        const tbody = document.getElementById('worktime-tbody');
        tbody.innerHTML = '';
        
        // 计算统计信息
        let totalRequirements = 0;
        let totalWorktime = 0;
        
        data.forEach(stats => {
            totalRequirements += stats.total_requirements;
            totalWorktime += stats.total_worktime;
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${stats.statistics_period}</td>
                <td>${stats.project_name || '未指定项目'}</td>
                <td>${stats.system_name}</td>
                <td>${stats.total_requirements}</td>
                <td>${stats.total_worktime.toFixed(1)}</td>
                <td>${stats.completed_requirements}</td>
                <td>${stats.completed_worktime.toFixed(1)}</td>
                <td>${stats.in_progress_requirements}</td>
                <td>${stats.in_progress_worktime.toFixed(1)}</td>
                <td>${stats.non_transactional_requirements}</td>
                <td>${stats.transactional_requirements}</td>
                <td><button class="btn btn-sm" onclick="goToProjectDetail('${stats.statistics_period}', '${stats.project_name || ''}')">查看</button></td>
            `;
            tbody.appendChild(row);
        });
        
        // 更新筛选状态显示
        updateFilterStatus(data.length, totalRequirements, totalWorktime, filters);
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="12" style="text-align: center; color: #6c757d;">暂无数据</td></tr>';
        }
        
        // 隐藏加载状态
        showLoadingState(false);
        
    } catch (error) {
        console.error('加载工时统计数据失败:', error);
        showMessage('加载工时统计数据失败', 'error');
        // 隐藏加载状态
        showLoadingState(false);
    }
}

// 显示工时明细
async function showWorktimeDetail(period, project, system) {
    try {
        const params = new URLSearchParams({
            period: period,
            project: project,
            system: system
        });
        
        const response = await fetch(`/api/project-worktime-details?${params}`);
        const data = await response.json();
        
        // 更新弹窗标题信息
        const detailInfo = document.getElementById('detail-info');
        detailInfo.innerHTML = `
            <p><strong>统计周期：</strong>${period}</p>
            <p><strong>所属项目：</strong>${project}</p>
            <p><strong>系统名称：</strong>${system}</p>
        `;
        
        // 填充明细表格
        const tbody = document.getElementById('detail-tbody');
        tbody.innerHTML = '';
        
        data.forEach(detail => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${detail.date_field || '-'}</td>
                <td>${detail.requirement_type || '-'}</td>
                <td>${detail.status || '-'}</td>
                <td>${detail.worktime.toFixed(1)}</td>
            `;
            tbody.appendChild(row);
        });
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #6c757d;">暂无明细数据</td></tr>';
        }
        
        // 显示弹窗
        document.getElementById('detail-modal').style.display = 'block';
        
    } catch (error) {
        console.error('加载工时明细失败:', error);
        showMessage('加载工时明细失败', 'error');
    }
}

// 跳转到项目详情页
function goToProjectDetail(period, project) {
    const params = new URLSearchParams({
        period: period,
        project: project
    });
    window.location.href = `/project-detail?${params}`;
}

// 跳转到成员工时详情页
function goToMemberWorktimeDetail(name, period) {
    const params = new URLSearchParams({
        name: name,
        period: period
    });
    window.location.href = `/member-worktime-detail?${params}`;
}

// 关闭明细弹窗
function closeDetailModal() {
    document.getElementById('detail-modal').style.display = 'none';
}

// 点击弹窗外部关闭
window.onclick = function(event) {
    const detailModal = document.getElementById('detail-modal');
    
    if (event.target === detailModal) {
        detailModal.style.display = 'none';
    }
}

// 显示加载状态
function showLoadingState(isLoading) {
    const tbody = document.getElementById('worktime-tbody');
    const filterButtons = document.querySelectorAll('.filter-buttons .btn');
    
    if (isLoading) {
        tbody.innerHTML = '<tr><td colspan="12" style="text-align: center; color: #667eea;"><i>正在加载数据...</i></td></tr>';
        filterButtons.forEach(btn => btn.disabled = true);
    } else {
        filterButtons.forEach(btn => btn.disabled = false);
    }
}

// 显示消息提示
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 10px 20px;
        border-radius: 4px;
        color: white;
        z-index: 1000;
        ${type === 'error' ? 'background-color: #dc3545;' : 'background-color: #28a745;'}
    `;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}

// 应用筛选条件
function applyFilters() {
    const filters = {
        period: document.getElementById('period-filter').value,
        project: document.getElementById('project-filter').value.trim(),
        system: document.getElementById('system-filter').value.trim()
    };
    
    // 移除空值
    Object.keys(filters).forEach(key => {
        if (!filters[key]) {
            delete filters[key];
        }
    });
    
    // 显示加载状态
    showLoadingState(true);
    
    loadWorktimeStats(filters);
}

// 清空筛选条件
function clearFilters() {
    document.getElementById('period-filter').value = '';
    document.getElementById('project-filter').value = '';
    document.getElementById('system-filter').value = '';
    
    // 重新加载所有数据
    loadWorktimeStats();
}

// 加载筛选选项数据
async function loadFilterOptions() {
    try {
        const response = await fetch('/api/project-worktime-filter-options');
        const data = await response.json();
        
        // 存储到全局变量
        window.filterOptions = data;
        
        // 填充项目名称数据列表
        const projectList = document.getElementById('project-list');
        projectList.innerHTML = '';
        data.projects.forEach(project => {
            const option = document.createElement('option');
            option.value = project;
            projectList.appendChild(option);
        });
        
        // 填充系统名称数据列表
        const systemList = document.getElementById('system-list');
        systemList.innerHTML = '';
        data.systems.forEach(system => {
            const option = document.createElement('option');
            option.value = system;
            systemList.appendChild(option);
        });
        
        // 设置默认的统计周期为最新的周期
        if (data.periods && data.periods.length > 0) {
            document.getElementById('period-filter').value = data.periods[0];
        }
        
    } catch (error) {
        console.error('加载筛选选项失败:', error);
    }
}

// 更新筛选状态显示
function updateFilterStatus(recordCount, totalRequirements, totalWorktime, filters) {
    const statusElement = document.getElementById('filter-status');
    const countElement = document.getElementById('filter-count');
    const summaryElement = document.getElementById('filter-summary');
    
    // 更新记录数
    countElement.textContent = recordCount;
    
    // 构建筛选条件摘要
    const filterSummary = [];
    if (filters.period) {
        filterSummary.push(`周期: ${filters.period}`);
    }
    if (filters.project) {
        filterSummary.push(`项目: ${filters.project}`);
    }
    if (filters.system) {
        filterSummary.push(`系统: ${filters.system}`);
    }
    
    // 添加统计信息
    const statsInfo = [];
    if (totalRequirements > 0) {
        statsInfo.push(`总需求: ${totalRequirements}个`);
    }
    if (totalWorktime > 0) {
        statsInfo.push(`总工时: ${totalWorktime.toFixed(1)}人天`);
    }
    
    // 组合显示信息
    let summaryText = '';
    if (filterSummary.length > 0) {
        summaryText += `筛选条件: ${filterSummary.join(', ')}`;
    }
    if (statsInfo.length > 0) {
        if (summaryText) summaryText += ' | ';
        summaryText += statsInfo.join(', ');
    }
    
    summaryElement.textContent = summaryText;
    
    // 显示或隐藏状态栏
    if (recordCount > 0 || Object.keys(filters).length > 0) {
        statusElement.style.display = 'block';
        statusElement.classList.add('show');
    } else {
        statusElement.style.display = 'none';
        statusElement.classList.remove('show');
    }
}

// 初始化筛选功能
function initializeFilters() {
    // 为筛选输入框添加回车键监听
    const filterInputs = document.querySelectorAll('.filter-input');
    filterInputs.forEach(input => {
        input.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                applyFilters();
            }
        });
    });
    
    // 为成员工时筛选输入框添加回车键监听
    const memberWorktimeFilterInputs = document.querySelectorAll('#member-worktime-tab .filter-input');
    memberWorktimeFilterInputs.forEach(input => {
        input.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                applyMemberWorktimeFilters();
            }
        });
    });
    
    // 加载筛选选项
    loadFilterOptions();
    loadMemberWorktimeFilterOptions();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadMemberWorktimeData();
    initializeFilters();
});